package com.example.teesystem.common.utils;



import com.example.teesystem.entity.AuthenticationInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 处理用户登录和身份验证以及权限验证
 * @author punch
 * @data 2021-09-27 11:03
 */
public class AuthenticationUtil {
    private static final int TIME_OUT = 60000;

    //保存用户的登录信息
    private static final Map<String, AuthenticationInfo> identityInfo = new ConcurrentHashMap<>();

    //插入用户登录信息
    public static void addInfo(int uid, String token) {
        AuthenticationInfo authenticationInfo = new AuthenticationInfo(token);
        identityInfo.remove(String.valueOf(uid));
        identityInfo.put(String.valueOf(uid), authenticationInfo);
    }

    //更新用户登录信息
    public static void updateInfoByUid(int uid, AuthenticationInfo authenticationInfo) {
        identityInfo.put(String.valueOf(uid), authenticationInfo);
    }

    //删除用户登录信息
    public static void deleteInfoByUid(int uid) {
        //先判断是否存在，存在就删除
        if (!identityInfo.containsKey(String.valueOf(uid))) {
            return;
        }
        identityInfo.remove(String.valueOf(uid));
    }

    public static Boolean isEffective(int uid){
        AuthenticationInfo authenticationInfo = identityInfo.get(String.valueOf(uid));
        if(authenticationInfo == null){
            return false;
        }
        if (TimeUtil.getSecondTimestamp() - authenticationInfo.getTheLastUseSecond()>=TIME_OUT){
            return false;
        }
        authenticationInfo.setTheLastUseSecond(TimeUtil.getSecondTimestamp());
        updateInfoByUid(uid, authenticationInfo);
        return true;
    }

    public static AuthenticationInfo getAuthenticationInfo(int uid){
        return identityInfo.get(String.valueOf(uid));
    }

    public static Boolean isExist(int uid){
        return identityInfo.containsKey(String.valueOf(uid));
    }

}
